var express = require('express');
var router = express.Router();

const {request, response} = require("express");
const{ Sequelize,DataTypes } = require('sequelize');
const orm = require('../util/connect').orm()

const user = orm.import('../sequelize/models/user.model');
const login = orm.import('../sequelize/models/login.model');
const employee = orm.import('../sequelize/models/employee.model')
const consumer = orm.import('../sequelize/models/consumer.model');

const jwt = require('jsonwebtoken');
const secretKey = 'justatest'

/* GET users listing. */

//匹配用户生成token
router.post('/check',(req,res) => {
    console.log(req.body);
    const username=req.body.user.UserName;
    const pwd = req.body.user.PassWord;
    login.findOne({
        where:{
            user_name:username,
            pwd:pwd
        },
        attributes:['uid','user_name'],
        include:[{
            model: user,
            attributes:['identity','tel'],
            as:user
        },
        {
            model:employee,
            attributes:['is_admin'],
            as:employee
        }],
        raw:true
    })
        .then(result=>{
            console.log(result);
            if(result !=null){
                const tokenStr = jwt.sign(result,secretKey,{expiresIn:'1h'})
                res.send({
                    code:200,
                    msg:"登录成功",
                    token:'Bearer '+tokenStr,
                    data:result['user.identity']
                })
            }else{
                res.send({
                    code:400,
                    msg:'用户名或密码输入错误,请重新输入'
                })
            }
        })

})
//退出登录接口
router.post('/logout',(req,res)=>{
    const logout =login.update({
        status:'离线'
    },{
        where:{
            uid:req.user.uid
        }
    })
    res.send({
        code:200,
        msg:'已退出登录'
    })
})
//注销接口
router.delete('/logoff',(req,res)=>{
    const username=req.body.UserName;
    const pwd = req.body.PassWord;
    const logoff =login.destroy({
        user_name:username,
        pwd:pwd
    }).catch(error=>{
        res.send({
            code:500,
            msg:'注销失败'
        })
    })
    res.send({
        code:200,
        msg:'成功注销'
    })
})


module.exports = router;
